package com.cupk.service.impl;

import com.cupk.mapper.RecordMapper;
import com.cupk.mapper.StageMapper;
import com.cupk.pojo.Record;
import com.cupk.pojo.Result;
import com.cupk.pojo.Stage;
import com.cupk.pojo.Student;
import com.cupk.service.RecordService;
import com.cupk.utils.HttpUtil;
import com.cupk.utils.ImgUtil;
import com.cupk.utils.OCRUtil;
import com.google.gson.Gson;
import net.bytebuddy.asm.Advice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Service
public class RecordServiceImpl implements RecordService {
    @Autowired
    private RecordMapper recordMapper;
    @Autowired
    private StageMapper stageMapper;


    @Override
    public Record dealResult(Record m) {
        Integer topicId = m.getTopicId();
        Stage s = stageMapper.getRuleByTopic(topicId);
        Integer rule = s.getRule();
        if (rule == Stage.AUTO_APPROVE_FORM) {
            m.setStatus(1);
        } else if (rule == Stage.MANUAL_APPROVE_FORM) {
            m.setStatus(0);
        } else if (rule == Stage.IMAGE_SIMILARITY_COMPARISON) {
            m.setStatus(0);
            String userImg = m.getAnswer();
            String refImg = s.getStandard();
            double similarityPercent = ImgUtil.LoadingCalculateSimilarity(userImg, refImg);
            m.setResult(String.valueOf(similarityPercent));
            if (similarityPercent > 0.95) {
                m.setStatus(1);
            }
        } else if (rule == Stage.OCR_FIELD_CONTAINS) {
            m.setStatus(0);
            String requestString = s.getStandard();
            String userImg = m.getAnswer();
            if (OCRUtil.judgeSpecialText(requestString, userImg)) {
                m.setStatus(1);
            }
        } else if (rule == Stage.OCR_FIELD_RECOGNITION) {
            String userImg = m.getAnswer();
            String userString = OCRUtil.judgePaymentTickets(userImg);
            m.setStatus(0);
            m.setResult(userString);
        }
        return m;
    }

    @Override
    public void addRecord(Record l) {
        Integer stuId = l.getStuId(), topicId = l.getTopicId();
        Record already = recordMapper.getRecordByStuAndTopic(stuId, topicId);
        if (already == null) {
            recordMapper.addRecord(l);
        } else {
            recordMapper.updateRecord(l);
        }
    }

    @Override
    public List<Record> getPreparingList(Integer stageId) {
        List<Record> rec = recordMapper.getPreparingList(stageId);
        return rec;
    }

    @Override
    public List<Record> getFinishList(Integer stageId) {
        List<Record> rec = recordMapper.getFinishList(stageId);
        return rec;
    }

    @Override
    public Record getRecordById(Integer id) {
        return recordMapper.getRecordById(id);
    }

    @Override
    public void PushMessage(String accessToken, String openId, String stageName, String userName, Integer status, String comment) {
        String requestUrl = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + accessToken;
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String strNow = now.format(formatter);
        String result;
        if (status == 1) {
            result = "审核通过";
        } else {
            result = "审核驳回";
        }
        Map<String, Object> rec = new HashMap<>();
        rec.put("template_id", "GbTDJYYfVhS4xOaQl_CAqjvVL5frAIFcvGYtbXFad7c");
        rec.put("miniprogram_state", "trial");
        rec.put("lang", "zh_CN");
        rec.put("page", "pages/index/index");
        rec.put("touser", openId);
        Gson gson = new Gson();
        Map<String, Object> data = new HashMap<>();
        // stageName
        Map<String, Object> value = new HashMap<>();
        value.put("value",stageName);
        data.put("thing6", value);
        // strNow
        value = new HashMap<>();
        value.put("value",strNow);
        data.put("date2", value);
        //userName
        value = new HashMap<>();
        value.put("value",userName);
        data.put("name3", value);
        //result
        value = new HashMap<>();
        value.put("value",result);
        data.put("thing40", value);
        //comment
        value = new HashMap<>();
        value.put("value",comment);
        data.put("thing4", value);

        rec.put("data", data);
        String recJson = gson.toJson(rec);
        String res = HttpUtil.post(requestUrl, recJson);
        System.out.println(res);
    }

    @Override
    public void acceptRecord(Integer stageId, String comment, Integer stuId) {
        recordMapper.acceptRecord(stageId, comment, stuId);
    }


    @Override
    public void rejectRecord(Integer stageId, String comment, Integer stuId) {
        recordMapper.rejectRecord(stageId, comment, stuId);
    }

    @Override
    public List<Record> getCommentList(Integer stageId, Integer userId) {
        return recordMapper.getRecordList(stageId, userId);
    }

    @Override
    public List<Record> getDetailList(Integer stageId, Integer stuId) {
        return recordMapper.getRecordList(stageId, stuId);
    }

    @Override
    public void acceptRecordByTransaction(Integer id, String res) {
        recordMapper.acceptRecordByTransaction(id, res);
    }

    @Override
    public List<Map<String, Object>> getAllInfoByStage(Integer id, Integer status) {
        List<Map<String, Object>> records = recordMapper.getAllInfoByStage(id, status);
        Map<Integer, Map<String, Object>> res = new HashMap<>();
        for (Map<String, Object> record : records) {
            Integer stuId = (Integer) record.get("stu_id");
            if (!res.containsKey(stuId)) {
                Map<String, Object> studentDetails = new HashMap<>();
                studentDetails.put("stu_id_card", record.get("stu_id_card"));
                studentDetails.put("name", record.get("name"));
                studentDetails.put("identity_card", record.get("identity_card"));
                studentDetails.put("grade", record.get("grade"));
                studentDetails.put("college", record.get("college"));
                studentDetails.put("major", record.get("major"));
                studentDetails.put("classes", record.get("classes"));
                studentDetails.put("phone", record.get("phone"));
                res.put(stuId, studentDetails);
            }
            res.get(stuId).put((String) record.get("question_text"), record.get("answer"));
        }
        return new ArrayList<>(res.values());
    }

    @Override
    public List<Map<String, Object>> divideMinute(Integer matchId) {
        return recordMapper.divideMinute(matchId);
    }

    @Override
    public List<Map<String, Object>> divideGroupByMajorAndGrade(Integer matchId) {
        return recordMapper.divideGroupByMajorAndGrade(matchId);
    }

    @Override
    public List<Map<String, Object>> divideGroupByGrade(Integer matchId) {
        return recordMapper.divideGroupByGrade(matchId);
    }
}